<template>
  <div id="login">
    <a-spin :spinning="submitting" :tip="l('LogIningWithThreeDot')">
      <h1 class="header">欢迎登录</h1>
      <!-- 租户切换 -->
      <div v-if="showTenantChange" style="padding-bottom: 20px">
        <tenant-change />
      </div>

      <a-form :model="form" @submit="login($event)" ref="formRef">
        <a-form-item
          name="userNameOrEmailAddress"
          :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
        >
          <a-input v-model:value="form.userNameOrEmailAddress" :placeholder="l('UserNameOrEmail')">
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>
        <a-form-item
          name="password"
          :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
        >
          <a-input
            v-model:value="form.password"
            :placeholder="l('Password')"
            type="password"
            autoComplete="“off”"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>
        <a-form-item
          v-if="useCaptcha"
          :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
          name="verificationCode"
        >
          <captcha
            v-model="form.verificationCode"
            ref="captcha"
            :placeholder="l('CAPTCHA')"
            :primaryKey="primaryKey"
            :type="captchaType"
            @update:modelValue="getChange($event)"
          />
        </a-form-item>
        <a-form-item>
          <a-button
            block
            class="login-bth"
            type="primary"
            html-type="submit"
            @click="login($event)"
          >
            {{ l('LogIn') }}
          </a-button>
        </a-form-item>
      </a-form>

      <div>
        <!-- 用户注册 -->
        <span v-if="isSelfRegistrationAllowed">
          <router-link to="/account/register">{{ l('CreateAnAccount') }}</router-link>
        </span>
        <!-- <span class="text-right" style="float: right" v-if="isSelfRegistrationAllowed"> -->
        <span class="text-right" style="float: right">
          <router-link to="/account/forgot-password">{{ l('ForgotPassword') }}</router-link>
        </span>
        <!--分割线 垂直分割线-->
        <a-divider type="vertical" />
        <!-- 租户注册 -->
        <span v-if="isTenantSelfRegistrationAllowed">
          <router-link to="/account/tenant-register">{{ l('TenantRegister') }}</router-link>
          <a-divider type="vertical" />
          <!-- <span>{{ l('PleaseSeeTheFullSystemThroughTenantRegistration') }}</span> -->
        </span>
      </div>
      <div style="padding-top: 100px; text-align: center">
        {{ l('ThisSystemIsRecommendedToUse') }}
        <a href="javascript:;" @click="downloadBrowser()">&nbsp;{{ l('GoogleChrome') }}</a>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import { Captcha } from '../components';
  import { abpService, appSessionService } from '/@/shared/abp';
  import { loginService } from './login.service';
  import { TenantChange } from '../tenant-change';
  import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
  import { defineComponent } from 'vue';
  import { AppConsts } from '/@/abpPro/AppConsts';
  import { AuthenticateModel } from '/@/shared/service-proxies/service-proxies';
  export default defineComponent({
    components: {
      Captcha,
      TenantChange,
      UserOutlined,
      LockOutlined,
    },
    mixins: [AppComponentBase],
    data() {
      return {
        isSubmitting: false, // 提交中
        tmpPrimaryKey: undefined,
        verificationImgUrl: undefined, // 验证码地址
        form: new AuthenticateModel(),
      };
    },
    computed: {
      primaryKey() {
        // 验证码主键
        return this.form.userNameOrEmailAddress;
      },
      submitting() {
        // 提交中
        return this.isSubmitting;
      },
      externalLoginProviders() {
        // 第三方登陆提供者
        return loginService.externalLoginProviders;
      },
      multiTenancySideIsTeanant() {
        // 是否已选中租户
        return appSessionService.tenantId > 0;
      },
      isTenantSelfRegistrationAllowed() {
        // 是否允许注册租户
        if (appSessionService.tenantId) {
          return false;
        }
        return abpService.abp.setting.getBoolean(
          'App.HostManagement.AllowSelfOnTenantRegistration',
        );
      },
      isMultiTenancyEnabled() {
        // 是否启用多租户
        return abpService.abp.multiTenancy.isEnabled;
      },
      isSelfRegistrationAllowed() {
        return abpService.abp.setting.getBoolean('App.Shared.AllowSelfRegistrationUser');
      },
      useCaptcha() {
        // 是否使用登陆验证码
        return abpService.abp.setting.getBoolean('App.Shared.UseCaptchaOnUserLogin');
      },
      captchaType() {
        // 验证码类型
        if (appSessionService.tenantId) {
          return AppConsts.settings.SharedSettings.UseCaptchaOnUserLogin;
        } else {
          return AppConsts.settings.SharedSettings.UseCaptchaOnUserLogin;
        }
      },
      captchaLength() {
        // 验证码长度
        return abpService.abp.setting.getInt('App.CaptchaOnUserLoginLength');
      },
      enabledExternalLoginTypes() {
        // 第三方登陆的类型
        return JSON.parse(abpService.abp.setting.get('App.UserManagement.ExternalLoginProviders'));
      },
      showTenantChange: () => {
        return abpService.abp.multiTenancy.isEnabled;
      },
    },
    watch: {},
    created() {
      loginService.initExternalLoginProviders().then(() => {});
      if (appSessionService.userId > 0 && loginService.getReturnUrl()) {
        appSessionService.session.updateUserSignInToken().then((result) => {
          const initialReturnUrl = loginService.getReturnUrl();
          const returnUrl =
            initialReturnUrl +
            (initialReturnUrl.indexOf('?') >= 0 ? '&' : '?') +
            'accessToken=' +
            result.signInToken +
            '&userId=' +
            result.encodedUserId +
            '&tenantId=' +
            result.encodedTenantId;

          location.href = returnUrl;
        });
      }
    },
    methods: {
      /** 验证码改变触发事件 */
      getChange(val) {
        this.form.verificationCode = val;
      },
      /** 登录 */
      login(e) {
        e.preventDefault();
        (this.$refs.formRef as any).validate().then(() => {
          loginService.authenticateModel = this.form;
          loginService.authenticate(
            () => {},
            () => {
              if (this.$refs.captcha) {
                (this.$refs.captcha as any).clearImg();
              }
            },
            () => {
              this.isSubmitting = false;
            },
          );
        });
      },
      /** 下载谷歌浏览器 */
      downloadBrowser() {
        let str = `${AppConsts.remoteServiceBaseUrl}/Download/chrome64_windows_installer.exe`;
        window.open(str);
      },
    },
  });
</script>

<style lang="less" scoped>
  @import './login.less';
</style>
